package com.ws.exer;

import java.util.Arrays;

/*
算法的考查:数组的复制、反转、查找(线性查找、二分法查找)

 */
public class ArrayExercise6 {
    public static void main(String[] args) {

        String[] arr = new String[]{"JJ", "DD", "MM", "BB", "GG", "AA"};

        //数组的复制
        String[] arr1 = new String[arr.length];
        for (int i = 0; i < arr1.length; i++) {
            arr1[i] = arr[i];
        }
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr1));


        //数组的反转 [JJ, DD, MM, BB, GG, AA]
        //方法一
        for (int i = 0; i < arr1.length / 2; i++) {
            String temp = arr1[i];
            arr1[i] = arr1[arr1.length - i - 1];
            arr1[arr1.length - i - 1] = temp;
        }
        System.out.println(Arrays.toString(arr1));

        //方法二
        for (int i = 0, j = arr1.length - 1; i < j; i++, j--) {
            String emp = arr1[i];
            arr1[i] = arr1[j];
            arr1[j] = emp;
        }
        System.out.println(Arrays.toString(arr1));


        //查找（或搜索）
        //线性查找
        boolean isFlag = true;
        String dest = "CC";
        for (int i = 0; i  < arr.length; i++) {
            if (arr[i].equals(dest)) {
                System.out.println("找到了相同的值，位置为：" + i);
                isFlag = false;
                break;
            }
        }
        if (isFlag) {
            System.out.println("没找到");
        }

        //二分法查找：比较快
        //前提：索要查找的数组必须有序
        int[] arr2 = new int[]{-98,-34,2,34,54,66,79,105,210,333};
        int dest1 = -34;
        int head = 0; //初始的首索引
        int end = arr2.length - 1; //初始的末索引 9
        boolean isFlag2 = true;
        int i = 0;//查询次数
        while (head <= end) {
            i++;
            int middle = (head + end) / 2;
            if (dest1 == arr2[middle]) {
                System.out.println("找到了指定的元素，位置为：" + middle);
                isFlag2 = false;
                break;
            } else if (arr2[middle] > dest1) {//查找到的值大于要查找的
                end = middle - 1; //往前找
            } else {
                head = middle + 1; //往后找
            }

        }
        System.out.println("查找了：" + i);
        if (isFlag2) {
            System.out.println("没有找到该元素");
        }

    }
}
